<template>
	<view class="" style="background-image: linear-gradient(to bottom, #dceaff, #ffffff);">
		<!-- 加载状态 -->
		<view v-if="loading" class="loading-container">
			<van-loading type="spinner" color="#3c91ff" size="large" />
			<text style="margin-top: 10rpx; color: #3c91ff;">加载中...</text>
		</view>

		<view class="">
			<van-cell-group inset placeholder-style="#3c91ff">
				<!-- 楼栋输入 -->
				<van-field @change="buildingIpt" :value="building" label="栋楼" :placeholder-style="{ color: '#3c91ff' }"
					placeholder="输入栋楼名称" input-align="right"></van-field>

				<!-- 详细地址输入 -->
				<van-field @change="detailAddressIpt" :value="detailAddress" label="详细地址"
					:placeholder-style="{ color: '#3c91ff' }" placeholder="输入门牌号" input-align="right"></van-field>

				<!-- 姓名输入 -->
				<van-field @change="nameIpt" :value="name" label="姓名" placeholder="输入姓名"
					input-align="right"></van-field>

				<!-- 联系电话输入 -->
				<van-field @change="phoneIpt" :value="phone" label="联系电话" placeholder="输入联系电话"
					input-align="right"></van-field>

				<!-- 默认地址切换 -->
				<van-cell use-label-slot="true" title="默认地址">
					<view>
						<van-switch :checked="isDefault === 1" @change="onDefaultChange" />
					</view>
				</van-cell>

				<!-- 地址说明 -->
				<van-cell title="地址说明" is-link @click="showAddressExplanation" />
			</van-cell-group>
		</view>
		<view style="padding: 80rpx 0;width: 100%;">
			<button
				style="background-color: #3c91ff; color: white; border-radius: 50rpx; width: 90%; margin: 0 auto;font-size: 36rpx;height: 100rpx;line-height: 100rpx;"
				@click="submitAddress" :disabled="loading">
				{{ loading ? '保存中...' : (id ? '修改地址' : '新增地址') }}
			</button>
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onShow,
		onUnload
	} from '@dcloudio/uni-app';
	import {
		ref,
		watch
	} from 'vue';


	import {
		getCampusAddress,
		deleteCampusAddress,
		getCampusAddressById
	} from '@/package/api/selList.js';
	import {
		updateCampusAddress
	} from '@/package/api/update.js';
	import {
		addCampusAddress
	} from '@/package/api/insertList.js';

	// 状态管理
	const loading = ref(false);
	const id = ref(null);
	const userId = ref(null);
	const building = ref('');
	const detailAddress = ref('');
	const name = ref('');
	const phone = ref('');
	const isDefault = ref(0);
	const checked = ref(false);

	// 获取用户ID
	const getUserId = () => {
		return uni.getStorageSync("user_id") || null;
	};

	// 工具函数
	const showToast = (title, icon = 'none') => {
		uni.showToast({
			title,
			icon,
			duration: 2000
		});
	};
	const showLoading = (title = '加载中...') => {
		loading.value = true;
		uni.showLoading({
			title,
			mask: true
		});
	};
	const hideLoading = () => {
		loading.value = false;
		uni.hideLoading();
	};

	// 输入处理
	const buildingIpt = (e) => building.value = e.detail;
	const detailAddressIpt = (e) => detailAddress.value = e.detail;
	const nameIpt = (e) => name.value = e.detail;
	const phoneIpt = (e) => phone.value = e.detail;

	// 默认地址切换
	const onDefaultChange = () => {
		isDefault.value = isDefault.value === 1 ? 0 : 1;
		checked.value = !checked.value;
	};

	// 提交地址
	const submitAddress = async () => {
		// 表单验证
		if (!building.value) {
			showToast('请输入栋楼名称', 'none');
			return;
		}
		if (!detailAddress.value) {
			showToast('请输入详细地址', 'none');
			return;
		}
		if (!name.value) {
			showToast('请输入姓名', 'none');
			return;
		}
		if (!phone.value || !/^(1)\d{10}$/.test(phone.value)) {
			showToast('请输入正确的手机号', 'none');
			return;
		}

		showLoading();
		try {
			// 构建地址数据（与后端属性完全对应）
			const addressData = {
				id: id.value,
				userId: userId.value,
				building: building.value,
				detailAddress: detailAddress.value,
				name: name.value,
				phone: phone.value,
				isDefault: isDefault.value
			};

			// const

			let res;
			if (id.value) {
				console.log("修改")
				// 修改地址
				res = await updateCampusAddress(JSON.stringify(addressData));
				showToast('地址修改成功', 'success');
			} else {
				console.log("新增")
				// 新增地址
				res = await addCampusAddress(JSON.stringify(addressData));
				console.log(res)
				showToast('地址添加成功', 'success');
			}

			if (res.code === 200) {
				// 提交成功后返回上一页
				uni.navigateBack();
			} else {
				showToast(res.message || '操作失败', 'none');
			}
		} catch (error) {
			console.error('提交地址失败', error);
			showToast('网络错误，请稍后再试', 'none');
		} finally {
			hideLoading();
		}
	};

	// 页面加载时解析编辑参数
	onLoad((options) => {
		userId.value = getUserId();


		// 处理编辑参数
		if (options.edit) {
			try {
				// 解码并解析JSON
				const addressData = JSON.parse(decodeURIComponent(options.edit));
				console.log('编辑参数解析结果:', addressData);

				// 初始化表单数据
				id.value = addressData.id;
				building.value = addressData.building || '';
				detailAddress.value = addressData.detailAddress || '';
				name.value = addressData.name || '';
				phone.value = addressData.phone || '';
				isDefault.value = addressData.isDefault || 0;
				checked.value = addressData.isDefault === 1;
				userId.value = addressData.userId || getUserId();

				console.log('编辑模式初始化成功');
			} catch (error) {
				console.error('编辑参数解析失败:', error);
				showToast('编辑参数异常，请重试', 'none');
			}
		}
	});

	// 监听默认地址变化
	watch(() => isDefault.value, (newVal) => {
		checked.value = newVal === 1;
	});

	// 页面显示时处理
	onShow(() => {
		// 可以在此处添加显示时的逻辑
	});

	// 页面卸载时处理
	onUnload(() => {
		// 可以在此处添加卸载时的逻辑
	});

	// 地址声明说明
	const showAddressExplanation = () => {
		uni.showModal({
			title: '地址声明',
			content: '若列表无想要的地址，选择楼栋可选择据目的地最近的建筑物，并在详细地址写明地点',
			showCancel: false,
			confirmText: '确定',
		});
	}


	// 其他逻辑...（保持不变）
</script>

<style scoped>
	::v-deep .van-cell__title {
		font-size: 32rpx;
		margin: 20rpx 0;
		padding-left: 20rpx;
		color: #000;
	}

	::v-deep .van-field__body {
		height: 100%;
	}

	::v-deep .van-field__label {
		font-size: 32rpx;
		color: #000;
	}

	::v-deep .input-placeholder {
		color: #3c91ff;
	}

	::v-deep .van-cell__value {
		color: #3c91ff;
		font-size: 32rpx;
	}

	::v-deep .van-cell {
		align-items: center;
		font-size: 32rpx;
	}

	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 100vh;
		background-color: rgba(255, 255, 255, 0.8);
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 999;
	}
</style>